package com.yhy.wxzn.wcs.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yhy.wxzn.common.exception.WmsBusinessException;
import com.yhy.wxzn.wcs.device.rgv.enums.NodeStatus;
import com.yhy.wxzn.wcs.device.rgv.enums.NodeType;
import com.yhy.wxzn.wcs.entity.WcsMapDate;
import com.yhy.wxzn.wcs.utils.MapImportUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import com.yhy.wxzn.wcs.entity.WcsMapInfo;
import com.yhy.wxzn.wcs.service.IWcsMapInfoService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 地图配置
 * @Author: jeecg-boot
 * @Date:   2023-10-31
 * @Version: V1.0
 */
@RestController
@RequestMapping("/wcs/wcsMapInfo")
@Slf4j
public class WcsMapInfoController extends JeecgController<WcsMapInfo, IWcsMapInfoService> {
	@Autowired
	private IWcsMapInfoService wcsMapInfoService;

	/**
	 * 分页列表查询
	 *
	 * @param wcsMapInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "地图配置-分页列表查询")
	@ApiOperation(value="地图配置-分页列表查询", notes="地图配置-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(WcsMapInfo wcsMapInfo,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<WcsMapInfo> queryWrapper = QueryGenerator.initQueryWrapper(wcsMapInfo, req.getParameterMap());
		Page<WcsMapInfo> page = new Page<WcsMapInfo>(pageNo, pageSize);
		IPage<WcsMapInfo> pageList = wcsMapInfoService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

//	/**
//	 *   添加
//	 *
//	 * @param wcsMapInfo
//	 * @return
//	 */
//	@AutoLog(value = "地图配置-添加")
//	@ApiOperation(value="地图配置-添加", notes="地图配置-添加")
//	@PostMapping(value = "/add")
//	public Result<?> add(@RequestBody WcsMapInfo wcsMapInfo) {
//		wcsMapInfo.setStatus(ValidEnums.ENABLE.getValue());
//		wcsMapInfo.setBeEmpty(YnEnums.Y.getValue());
//		wcsMapInfoService.save(wcsMapInfo);
//		return Result.OK("添加成功！",wcsMapInfo);
//	}

	 /**
	 *  编辑
	 *
	 * @param wcsMapInfo
	 * @return
	 */
	@AutoLog(value = "地图配置-编辑")
	@ApiOperation(value="地图配置-编辑", notes="地图配置-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody WcsMapInfo wcsMapInfo) {
		wcsMapInfoService.updateById(wcsMapInfo);
		return Result.OK("编辑成功!",wcsMapInfo);
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "地图配置-通过id删除")
	@ApiOperation(value="地图配置-通过id删除", notes="地图配置-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		wcsMapInfoService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "地图配置-批量删除")
	@ApiOperation(value="地图配置-批量删除", notes="地图配置-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.wcsMapInfoService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "地图配置-通过id查询")
	@ApiOperation(value="地图配置-通过id查询", notes="地图配置-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		WcsMapInfo wcsMapInfo = wcsMapInfoService.getById(id);
		if(wcsMapInfo==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(wcsMapInfo);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param wcsMapInfo
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WcsMapInfo wcsMapInfo) {
        return super.exportXls(request, wcsMapInfo, WcsMapInfo.class, "地图配置");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		Iterator iterator = fileMap.entrySet().iterator();
		if (iterator.hasNext()) {
			Map.Entry<String, MultipartFile> entity = (Map.Entry)iterator.next();
			MultipartFile file = entity.getValue();
			try {
				long start = System.currentTimeMillis();
				List<WcsMapInfo> mapInfos = MapImportUtils.importExcel(file.getInputStream());
				wcsMapInfoService.importMap(mapInfos);
				log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				Result var13 = Result.OK("地图信息导入成功","文件导入成功！");
				return var13;
			} catch (Exception e) {
				throw new WmsBusinessException(e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException ioException) {
					ioException.printStackTrace();
				}
			}
		} else {
			return Result.error("文件导入失败！");
		}
    }

	 /**
	  * 查询当前层节点
	  *
	  * @param floor
	  * @return
	  */
	 @GetMapping(value = "/floorCoordinate")
	 public Result<?> floorCoordinate(@RequestParam("floor") Integer floor) {
	 	int x = wcsMapInfoService.maxX();
	 	int y = wcsMapInfoService.maxY();
		 WcsMapDate[][] result = new WcsMapDate[x][y];
		 List<WcsMapInfo> mapInfos = wcsMapInfoService.getWcsMapInfoByFloor(floor);
		 for (WcsMapInfo mapInfo : mapInfos) {
		 	if (mapInfo.getX() == null || mapInfo.getY() ==null) continue;
			 WcsMapDate wcsMapDate = new WcsMapDate();
			 wcsMapDate.setId(mapInfo.getId());
			 wcsMapDate.setX(mapInfo.getX());
			 wcsMapDate.setY(mapInfo.getY());
			 wcsMapDate.setZ(mapInfo.getZ());
			 wcsMapDate.setBeDown(mapInfo.getBeDown());
			 wcsMapDate.setBeLeft(mapInfo.getBeLeft());
			 wcsMapDate.setBeRight(mapInfo.getBeRight());
			 wcsMapDate.setBeUp(mapInfo.getBeUp());
			 wcsMapDate.setNodeStatus(mapInfo.getNodeStatus());
			 wcsMapDate.setNodeType(NodeType.parseNodeType(mapInfo.getNodeType()).getDescribe() );
			 wcsMapDate.setNodeTypeEnum(mapInfo.getNodeType());
			 wcsMapDate.setOffsetX(mapInfo.getOffsetX());
			 wcsMapDate.setOffsetY(mapInfo.getOffsetY());


			 result[mapInfo.getX()-1][mapInfo.getY()-1] = wcsMapDate;
		 }
		 return Result.OK(result);
	 }



	 @GetMapping(value = "/maxX")
	 public Result<?> maxX() {
		 return Result.OK(wcsMapInfoService.maxX());
	 }

	 @GetMapping(value = "/maxY")
	 public Result<?> maxY() {
		 return Result.OK(wcsMapInfoService.maxY());
	 }

	 @GetMapping(value = "/maxZ")
	 public Result<?> maxZ() {
		 return Result.OK(wcsMapInfoService.maxZ());
	 }



	 @PutMapping(value = "/cargoStatus")
	 public Result<?> cargoStatus(String id,String status) {
	 	 NodeStatus.parse(status);
		 boolean b = wcsMapInfoService.cargoStatusById(id, status);
		 if (b){
			 return Result.OK("货物状态修改成功!",status);
		 }else {
			 return Result.error("货物状态修改失败!",status);
		 }
	 }


	 @PostMapping("/updateNodeStatus/{nodeId}/{nodeStatus}")
	 public Result<?> updateNodeStatus(@PathVariable String nodeId,@PathVariable String nodeStatus) {
		 UpdateWrapper<WcsMapInfo> updateWrapper = new UpdateWrapper<>();
		 updateWrapper.eq("id", nodeId);

		 WcsMapInfo wcsMapInfo = new WcsMapInfo();
		 wcsMapInfo.setNodeStatus(nodeStatus);

		 boolean updateResult = wcsMapInfoService.update(wcsMapInfo, updateWrapper);

		 if(updateResult) {
		 	return Result.OK("更新成功");
		 } else {
			 return Result.error("更新失败");
		 }
	 }
}
